package com.dc.bobaoge.project.v3.to.v2.business.core;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dc.bobaoge.common.em.OrderNumberEnum;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreTradeRecord;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreTradeRecordMapper;
import com.dc.bobaoge.project.v3.to.v2.business.core.util.OrderGenerateUtil;
import com.own.business.pay.common.constant.ConstantPay;
import com.own.business.pay.common.em.PayEnum;
import com.own.business.pay.mapper.BillHistoryMapper;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.business.sync.trigger.base.method.ResolveMethod;
import com.own.business.system.user.entity.po.SystemUserInfo;
import com.own.business.system.user.mapper.SystemUserInfoMapper;
import com.own.business.wallet.entity.po.Wallet;
import com.own.business.wallet.mapper.WalletMapper;
import com.own.component.common.exception.BusinessSimpleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * BillHistoryResolveMethod
 *
 * @author chenxueli
 * @date 2024-01-31 19:54:00
 */
@Slf4j
@Component
public class BillHistoryResolveMethod implements ResolveMethod {

    private static final Map<String, Integer> TRADE_TYPE_MAP = new HashMap<>() {{
        put(PayEnum.Method.WECHAT.getType(), 2);
        put(PayEnum.Method.ALIPAY.getType(), 1);
        put(PayEnum.Method.BALANCE.getType(), 3);
    }};
    private static final Map<Integer, Integer> COST_TYPE_MAP = new HashMap<>() {{
        put(3, 2);
        put(2, 1);
        put(1, 2);
    }};
    // 1 充值/ 2 订阅/ 3 发布消息/ 4 拼手气/ 5 打赏/6 信息分享红包/7 拼手气红包/8 管理员红包/9 拼手气虚拟商品/【10 用户已发布未通过消息退回】/【11 用户已发布删除消息退回】
    private static final Map<String, Integer> MAP = new HashMap<>() {{
        put(OrderNumberEnum.Income.INCOME_RECHARGE.getCategory(), 1);
        put(OrderNumberEnum.Pay.PAY_SUBSCRIBE_TITLE.getCategory(), 2);
        put(OrderNumberEnum.Pay.PAY_RED_PACKET.getCategory(), 3);
        put(OrderNumberEnum.Pay.PAY_REWARD.getCategory(), 5);
        put(OrderNumberEnum.Income.INCOME_RED_PACKET.getCategory(), 6);
        put(OrderNumberEnum.Refund.REFUND_RED_PACKET.getCategory(), 10);
    }};
    @Resource
    private BillHistoryMapper billHistoryMapper;
    @Resource
    private WalletMapper walletMapper;
    @Resource
    private SystemUserInfoMapper systemUserInfoMapper;
    @Resource
    private OldCoreTradeRecordMapper oldCoreTradeRecordMapper;

    /**
     * 修改的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void update(SyncTrigger trigger) {
        if (trigger.getNewStatus() != ConstantPay.Status.COMPLETE_SUCCESS) {
            log.debug("账单状态不是支付成功，不需要处理");
            return;
        }
        var history = billHistoryMapper.selectById(trigger.getTargetId());
        if (history == null) {
            throw new BusinessSimpleException("账单不存在");
        }
        if (history.getStatus() != ConstantPay.Status.COMPLETE_SUCCESS) {
            log.debug("账单状态不是支付成功，不需要处理");
            return;
        }
        // 直接新建账单信息
        var record = new OldCoreTradeRecord();
        // 查询用户信息
        var userInfo = getSystemUserInfoByUserId(history.getFkUserId());
        record.setUserPhone(userInfo == null ? "" : userInfo.getPhone());
        record.setUserId(history.getFkUserId());
        record.setCostType(COST_TYPE_MAP.get(history.getType()));
        record.setPayType(TRADE_TYPE_MAP.get(history.getTradeType()));
        if (history.getType() == ConstantPay.Type.REFUND) {
            var item = OrderGenerateUtil.resolveNoCheck(history.getOutRefundNo());
            if (item != null) {
                record.setTradeType(MAP.getOrDefault(item.category(), 16));
            } else {
                record.setTradeType(16);
            }
            record.setTradeMoney(history.getRefundAmount() + "");
        } else {
            var item = OrderGenerateUtil.resolveNoCheck(history.getOutTradeNo());
            if (item != null) {
                record.setTradeType(MAP.getOrDefault(item.category(), 16));
            } else {
                record.setTradeType(16);
            }
            record.setTradeMoney(history.getTotalAmount() + "");
        }
        // 查询用户当前的余额
        var wallet = getWalletByUserId(history.getFkUserId());
        record.setUserBalance(wallet != null ? wallet.getBalance() + "" : "0");
        record.setTradeTime(history.getTradeTime());
        oldCoreTradeRecordMapper.insert(record);
    }

    /**
     * 根据用户id查询钱包信息
     *
     * @param userId 用户id
     * @return 钱包信息
     */
    private Wallet getWalletByUserId(Long userId) {
        var wrapper = new LambdaQueryWrapper<Wallet>()
                .eq(Wallet::getFkUserId, userId);
        return walletMapper.selectOne(wrapper);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId 用户id
     * @return 用户信息
     */
    private SystemUserInfo getSystemUserInfoByUserId(Long userId) {
        var wrapper = new LambdaQueryWrapper<SystemUserInfo>()
                .eq(SystemUserInfo::getFkUserId, userId);
        return systemUserInfoMapper.selectOne(wrapper);
    }

    /**
     * 名称信息
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "bill_history";
    }

}
